﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AzureTosser.Services;
using System.Net;

namespace AzureTosser.Controllers
{
    [JSONPFilter]
    public class ReceiveController: AsyncController
    {
        public void IndexAsync(string pipe, string topic)
        {
            AsyncManager.OutstandingOperations.Increment();
            ITossBus bus = TossProviderFactory.Instance.Bus;
            var pipeDef = bus.GetPipeDefinition(pipe, true);
            if (pipeDef == null)
            {
                AsyncManager.Parameters["result"] = "Pipe not found.";
                AsyncManager.Parameters["state"] = (int)HttpStatusCode.BadRequest;
                AsyncManager.OutstandingOperations.Decrement();
            }
            else if (pipeDef.PipeType != PipeType.Receive)
            {
                AsyncManager.Parameters["result"] = "Pipe is not a sending pipe.";
                AsyncManager.Parameters["state"] = (int)HttpStatusCode.BadRequest;
                AsyncManager.OutstandingOperations.Decrement();
            }
            if (pipeDef != null)
            {
                Message msg = bus.Receive(pipeDef.Id, topic);
                AsyncManager.Parameters["message"] = msg;
                AsyncManager.OutstandingOperations.Decrement();
            }
        }
        public ActionResult IndexCompleted(string result, int state, Message message)
        {
            if (state == (int)HttpStatusCode.BadRequest)
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
            if (message == null)
            {
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                return Json("Internal server error", JsonRequestBehavior.AllowGet);
            }
            Response.CacheControl = "no-cache";
            Response.Headers.Add("scope", message.Scope);
            Response.Headers.Add("topic", message.Topic);
            return Json(message.Body, JsonRequestBehavior.AllowGet);
        }
    }
}